package com.wwz.config;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.wwz.annoation.PageParam;
import com.wwz.interceptor.ExHandlerInterceptor;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

@Configuration
public class ExWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new CustomerMethodArgumentResolver());
    }
    @Override
    public void  addInterceptors(InterceptorRegistry registry) {


    }


    class CustomerMethodArgumentResolver implements HandlerMethodArgumentResolver {

        @Override
        public boolean supportsParameter(MethodParameter methodParameter) {
            return methodParameter.hasParameterAnnotation(PageParam.class) || methodParameter.getParameterType().isAssignableFrom(RowBounds.class);
        }

        @Nullable
        @Override
        public Object resolveArgument(MethodParameter methodParameter, @Nullable ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, @Nullable WebDataBinderFactory webDataBinderFactory) throws Exception {
            Method method = methodParameter.getMethod();
            PageParam pageParam = methodParameter.getParameterAnnotation(PageParam.class);
            if (pageParam != null) {
                HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();
                String current = request.getParameter("current");
                String pageSize = request.getParameter("pageSize");
                int current$ = 0, pageSize$ = 0;
                if (!StringUtils.isEmpty(current)) {
                    current$ = Integer.valueOf(current);
                }
                if (!StringUtils.isEmpty(pageSize)) {
                    pageSize$ = Integer.valueOf(pageSize);
                }
                Page page = new Page(current$, pageSize$);
                PageHelper.startPage(current$, pageSize$);
                page.setSearchCount(true);
                return page;
            }
            return null;
        }
    }
}
